package com.supeng.PMdepot.netNew;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.supeng.PMdepot.R;
import com.supeng.PMdepot.common.Config;
import com.supeng.PMdepot.common.Constant;
import com.supeng.PMdepot.entity.ServiceResult;
import com.supeng.PMdepot.util.ToastUtils;
import com.supeng.PMdepot.widget.dialog.CProgressDialog;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadQueue;
import com.yanzhenjie.nohttp.download.DownloadRequest;
import com.yanzhenjie.nohttp.error.NetworkError;
import com.yanzhenjie.nohttp.error.NotFoundCacheError;
import com.yanzhenjie.nohttp.error.TimeoutError;
import com.yanzhenjie.nohttp.error.URLError;
import com.yanzhenjie.nohttp.error.UnKnownHostError;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.RequestQueue;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;
import com.yanzhenjie.nohttp.rest.StringRequest;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class CallServer {
    private static CallServer instance;

    public static CallServer getInstance() {
        if (instance == null)
            synchronized (CallServer.class) {
                if (instance == null)
                    instance = new CallServer();
            }
        return instance;
    }

    private RequestQueue mRequestQueue;
    private DownloadQueue mDownloadQueue;

    private CallServer() {
        mRequestQueue = NoHttp.newRequestQueue(5);
        mDownloadQueue = NoHttp.newDownloadQueue(1);

    }

    /**
     * http get
     *
     * @param what
     * @param url
     * @param msg
     * @param callBack
     * @param rspCls
     */
    public void get(final Activity context, int what, final String url, final String msg, final HttpListener<ServiceResult> callBack, final Class<?> rspCls) {
        // 创建请求对象。
        Request<String> request = NoHttp.createStringRequest(url, RequestMethod.GET);

        String token = Config.getUserInfo().getToken();
        if (!TextUtils.isEmpty(token)) {
            request.addHeader("Authorization", "bearer " + token);
        }

        mRequestQueue.add(what, request, new OnResponseListener<String>() {
            CProgressDialog mWaitDialog;
            @Override
            public void onSucceed(int what, Response<String> response) {
                String result = response.get();
                if (result != null && result.contains("已拒绝为此请求授权")) {
                    Intent intent = new Intent();
                    intent.setAction(Constant.NETWORK_ACTION_EXIT);
                    context.sendBroadcast(intent);
                    return;
                }
                ServiceResult rsp = null;
                try {
                    Gson gson = new Gson();
                    rsp = (ServiceResult) gson.fromJson(result, rspCls);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (callBack != null)
                    if ( rsp != null ) {
                        callBack.success(rsp);
                    } else {
                        ToastUtils.show(R.string.error_data);
                        callBack.failed("");
                    }
            }

            @Override
            public void onStart(int what) {
                // 请求开始，这里可以显示一个dialog
                if (!TextUtils.isEmpty(msg)) {
                    mWaitDialog = new CProgressDialog(context);
                    mWaitDialog.setMessage(msg);
                    mWaitDialog.setOwnerActivity(context);
                    mWaitDialog.setCancelable(true);
                    mWaitDialog.show();
                }
            }

            @Override
            public void onFinish(int what) {
                // 请求结束，这里关闭dialog
                if (mWaitDialog != null && mWaitDialog.isShowing()) {
                    Activity activity = mWaitDialog.getOwnerActivity();
                    if (activity != null && !activity.isFinishing()) {
                        mWaitDialog.dismiss();
                    }
                }
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                // 请求失败
                Throwable exception = response.getException();
                if (exception instanceof NetworkError) {// 网络不好
                    ToastUtils.show(R.string.error_please_check_network);
                } else if (exception instanceof TimeoutError) {// 请求超时
                    ToastUtils.show(R.string.error_timeout);
                } else if (exception instanceof UnKnownHostError) {// 找不到服务器
                    ToastUtils.show(R.string.error_not_found_server);
                } else if (exception instanceof URLError) {// URL是错的
                    ToastUtils.show(R.string.error_url_error);
                } else if (exception instanceof NotFoundCacheError) {
                    // 这个异常只会在仅仅查找缓存时没有找到缓存时返回
                    ToastUtils.show(R.string.error_not_found_cache);
                } else {
                    ToastUtils.show(R.string.error_unknow);
                }
                callBack.failed(exception.getMessage());
            }
        });
    }

    public void get(final Activity context, int what, final String url, Map<String, Object> map, final String msg, final HttpListener<ServiceResult> callBack, final Class<?> rspCls) {
        // 创建请求对象。
        Request<String> request = NoHttp.createStringRequest(url, RequestMethod.GET);

        String token = Config.getUserInfo().getToken();
        if (!TextUtils.isEmpty(token)) {
            request.addHeader("Authorization", "bearer " + token);
        }
        request.add(map);

        mRequestQueue.add(what, request, new OnResponseListener<String>() {
            CProgressDialog mWaitDialog;
            @Override
            public void onSucceed(int what, Response<String> response) {
                String result = response.get();
                if (result != null && result.contains("已拒绝为此请求授权")) {
                    Intent intent = new Intent();
                    intent.setAction(Constant.NETWORK_ACTION_EXIT);
                    context.sendBroadcast(intent);
                    return;
                }
                ServiceResult rsp = null;
                try {
                    Gson gson = new Gson();
                    rsp = (ServiceResult) gson.fromJson(result, rspCls);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (callBack != null)
                    if ( rsp != null ) {
                        callBack.success(rsp);
                    } else {
                        ToastUtils.show(R.string.error_data);
                        callBack.failed("");
                    }
            }

            @Override
            public void onStart(int what) {
                // 请求开始，这里可以显示一个dialog
                if (!TextUtils.isEmpty(msg)) {
                    mWaitDialog = new CProgressDialog(context);
                    mWaitDialog.setMessage(msg);
                    mWaitDialog.setOwnerActivity(context);
                    mWaitDialog.setCancelable(true);
                    mWaitDialog.show();
                }
            }

            @Override
            public void onFinish(int what) {
                // 请求结束，这里关闭dialog
                if (mWaitDialog != null && mWaitDialog.isShowing()) {
                    Activity activity = mWaitDialog.getOwnerActivity();
                    if (activity != null && !activity.isFinishing()) {
                        mWaitDialog.dismiss();
                    }
                }
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                // 请求失败
                Throwable exception = response.getException();
                if (exception instanceof NetworkError) {// 网络不好
                    ToastUtils.show(R.string.error_please_check_network);
                } else if (exception instanceof TimeoutError) {// 请求超时
                    ToastUtils.show(R.string.error_timeout);
                } else if (exception instanceof UnKnownHostError) {// 找不到服务器
                    ToastUtils.show(R.string.error_not_found_server);
                } else if (exception instanceof URLError) {// URL是错的
                    ToastUtils.show(R.string.error_url_error);
                } else if (exception instanceof NotFoundCacheError) {
                    // 这个异常只会在仅仅查找缓存时没有找到缓存时返回
                    ToastUtils.show(R.string.error_not_found_cache);
                } else {
                    ToastUtils.show(R.string.error_unknow);
                }
                callBack.failed(exception.getMessage());
            }
        });
    }

    public void post(final Activity context, int what, String url, JSONObject json, final String msg, final HttpListener<ServiceResult> callBack, final Class<?> rspCls) {
        // 创建请求对象。
        Request<String> request = NoHttp.createStringRequest(url, RequestMethod.POST);

        String token = Config.getUserInfo().getToken();
        if (!TextUtils.isEmpty(token)) {
            request.addHeader("Authorization", "bearer " + token);
        }
        // 提交普通String
        //request.setDefineRequestBody(String, ContentType);
        // 提交jsonObject对象，其实还是json字符串
        request.setDefineRequestBodyForJson(json);

        post(context, what, request, msg, callBack, rspCls);
    }
    
    public void post(final Activity context, int what, String url, Map<String, Object> map, final String msg, final HttpListener<ServiceResult> callBack, final Class<?> rspCls) {
        // 创建请求对象。
        Request<String> request = NoHttp.createStringRequest(url, RequestMethod.POST);
        // 添加请求参数。
        if (map == null) {
            map = new HashMap<>();
        }
        //request.add(map);
        String token = Config.getUserInfo().getToken();
        if (!TextUtils.isEmpty(token)) {
            request.addHeader("Authorization", "bearer " + token);
        }
        // 提交普通String
        //request.setDefineRequestBody(String, ContentType);
        // 提交jsonObject对象，其实还是json字符串
        request.setDefineRequestBodyForJson(new JSONObject(map));

        post(context, what, request, msg, callBack, rspCls);
    }

    public void postForm(final Activity context, int what, String url, Map<String, Object> map, final String msg, final HttpListener<ServiceResult> callBack, final Class<?> rspCls) {
        // 创建请求对象。
        Request<String> request =new StringRequest(url, RequestMethod.POST);
                //NoHttp.createStringRequest(url, RequestMethod.POST);
        // 添加请求参数。
        if (map == null) {
            map = new HashMap<>();
        }
        String token="";
        if(Config.isUserLogin()) {
            token= Config.getUserInfo().getToken();
        }
        if (!TextUtils.isEmpty(token)) {
            request.addHeader("Authorization", token);
        }

        request.add(map);
        request.setMultipartFormEnable(true);
       // request.setDefineRequestBody("username=A001&psd=123456","application/x-www-form-urlencoded");
        post(context, what, request, msg, callBack, rspCls);
    }


    public void post(final Activity context, int what, final Request<String> request, final String msg, final HttpListener<ServiceResult> callBack, final Class<?> rspCls) {
        mRequestQueue.add(what, request, new SimpleResponseListener<String>() {
            CProgressDialog mWaitDialog;
            @Override
            public void onSucceed(int what, Response<String> response) {
                String jsonObject = response.get();
                if (jsonObject != null && jsonObject.contains("已拒绝为此请求授权")) {
                    Intent intent = new Intent();
                    intent.setAction(Constant.NETWORK_ACTION_EXIT);
                    context.sendBroadcast(intent);
                    return;
                }
                ServiceResult rsp = null;
                try {
                    Gson gson = new Gson();
                    rsp = (ServiceResult) gson.fromJson(jsonObject, rspCls);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (callBack != null)
                    if ( rsp != null ) {
                        callBack.success(rsp);
                    } else {
                        ToastUtils.show(R.string.error_data);
                        callBack.failed("");
                    }
            }

            @Override
            public void onStart(int what) {
                // 请求开始，这里可以显示一个dialog
                if (!TextUtils.isEmpty(msg)) {
                    mWaitDialog = new CProgressDialog(context);
                    mWaitDialog.setMessage(msg);
                    mWaitDialog.setOwnerActivity(context);
                    mWaitDialog.setCancelable(true);
                    mWaitDialog.show();
                }
            }

            @Override
            public void onFinish(int what) {
                // 请求结束，这里关闭dialog
                if (mWaitDialog != null && mWaitDialog.isShowing()) {
                    Activity activity = mWaitDialog.getOwnerActivity();
                    if (activity != null && !activity.isFinishing()) {
                        mWaitDialog.dismiss();
                    }
                }
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                // 请求失败
                Throwable exception = response.getException();
                if (exception instanceof NetworkError) {// 网络不好
                    ToastUtils.show(R.string.error_please_check_network);
                } else if (exception instanceof TimeoutError) {// 请求超时
                    ToastUtils.show(R.string.error_timeout);
                } else if (exception instanceof UnKnownHostError) {// 找不到服务器
                    ToastUtils.show(R.string.error_not_found_server);
                } else if (exception instanceof URLError) {// URL是错的
                    ToastUtils.show(R.string.error_url_error);
                } else if (exception instanceof NotFoundCacheError) {
                    // 这个异常只会在仅仅查找缓存时没有找到缓存时返回
                    ToastUtils.show(R.string.error_not_found_cache);
                } else {
                    ToastUtils.show(R.string.error_unknow);
                }
                callBack.failed(exception.getMessage());
            }
        });
    }

    public void download(int what, DownloadRequest request, DownloadListener listener) {
        mDownloadQueue.add(what, request, listener);
    }
}
